import React, { useState, useEffect } from 'react'
import { User, Todo, TodoCreate, TodoStatus, TodoPriority, AdminStats } from '../types/todo'
import { adminApi } from '../services/adminApi'

interface AdminDashboardProps {}

const AdminDashboard: React.FC<AdminDashboardProps> = () => {
  const [users, setUsers] = useState<User[]>([])
  const [selectedUser, setSelectedUser] = useState<User | null>(null)
  const [userTodos, setUserTodos] = useState<Todo[]>([])
  const [stats, setStats] = useState<AdminStats | null>(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  
  // 新任务表单状态
  const [newTodo, setNewTodo] = useState<TodoCreate>({
    title: '',
    description: '',
    status: TodoStatus.PENDING,
    priority: TodoPriority.MEDIUM
  })
  const [showAddForm, setShowAddForm] = useState(false)
  const [showDeleteConfirm, setShowDeleteConfirm] = useState<{show: boolean, todoId: number | null, todoTitle: string}>({
    show: false, 
    todoId: null, 
    todoTitle: ''
  })

  // 获取所有用户
  const fetchUsers = async () => {
    try {
      setLoading(true)
      const response = await adminApi.getAllUsers()
      setUsers(response.data)
    } catch (err) {
      setError('获取用户列表失败')
      console.error('Error fetching users:', err)
    } finally {
      setLoading(false)
    }
  }

  // 获取用户任务
  const fetchUserTodos = async (userId: number) => {
    try {
      setLoading(true)
      const response = await adminApi.getUserTodos(userId)
      setUserTodos(response.data)
    } catch (err) {
      setError('获取用户任务失败')
      console.error('Error fetching user todos:', err)
    } finally {
      setLoading(false)
    }
  }

  // 获取统计信息
  const fetchStats = async () => {
    try {
      const response = await adminApi.getStats()
      setStats(response.data)
    } catch (err) {
      console.error('Error fetching stats:', err)
    }
  }

  // 删除任务
  const deleteTodoFromUser = async (todoId: number) => {
    if (!selectedUser) return

    try {
      setLoading(true)
      await adminApi.deleteTodo(selectedUser.id, todoId)
      
      // 重新获取用户任务
      await fetchUserTodos(selectedUser.id)
      
      setShowDeleteConfirm({show: false, todoId: null, todoTitle: ''})
      setError(null)
    } catch (err) {
      setError('删除任务失败')
      console.error('Error deleting todo:', err)
    } finally {
      setLoading(false)
    }
  }

  // 显示删除确认对话框
  const showDeleteConfirmDialog = (todoId: number, todoTitle: string) => {
    setShowDeleteConfirm({show: true, todoId, todoTitle})
  }

  // 分配任务给用户
  const assignTodoToUser = async () => {
    if (!selectedUser) {
      setError('请先选择用户')
      return
    }

    if (!newTodo.title.trim()) {
      setError('任务标题不能为空')
      return
    }

    try {
      setLoading(true)
      await adminApi.assignTodo(selectedUser.id, newTodo)
      
      // 重新获取用户任务
      await fetchUserTodos(selectedUser.id)
      
      // 重置表单
      setNewTodo({
        title: '',
        description: '',
        status: TodoStatus.PENDING,
        priority: TodoPriority.MEDIUM
      })
      setShowAddForm(false)
      setError(null)
    } catch (err) {
      setError('分配任务失败')
      console.error('Error assigning todo:', err)
    } finally {
      setLoading(false)
    }
  }

  // 选择用户
  const handleUserSelect = async (user: User) => {
    setSelectedUser(user)
    setUserTodos([])
    await fetchUserTodos(user.id)
  }

  // 初始化数据
  useEffect(() => {
    fetchUsers()
    fetchStats()
  }, [])

  // 状态和优先级的显示标签
  const getStatusLabel = (status: TodoStatus) => {
    const labels = {
      [TodoStatus.PENDING]: '待处理',
      [TodoStatus.IN_PROGRESS]: '进行中',
      [TodoStatus.COMPLETED]: '已完成'
    }
    return labels[status]
  }

  const getPriorityLabel = (priority: TodoPriority) => {
    const labels = {
      [TodoPriority.LOW]: '低',
      [TodoPriority.MEDIUM]: '中',
      [TodoPriority.HIGH]: '高'
    }
    return labels[priority]
  }

  return (
    <div className="min-h-screen bg-gray-50 p-6">
      <div className="max-w-7xl mx-auto">
        {/* 页面标题 */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-2">管理员面板</h1>
          <p className="text-gray-600">管理用户和分配任务</p>
        </div>

        {/* 错误提示 */}
        {error && (
          <div className="mb-4 bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
            {error}
          </div>
        )}

        {/* 删除确认对话框 */}
        {showDeleteConfirm.show && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
            <div className="bg-white rounded-lg p-6 max-w-md w-full mx-4">
              <h3 className="text-lg font-medium text-gray-900 mb-4">确认删除任务</h3>
              <p className="text-gray-600 mb-6">
                确定要删除任务 "{showDeleteConfirm.todoTitle}" 吗？此操作无法撤销。
              </p>
              <div className="flex gap-3 justify-end">
                <button
                  onClick={() => setShowDeleteConfirm({show: false, todoId: null, todoTitle: ''})}
                  className="px-4 py-2 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300 transition-colors"
                >
                  取消
                </button>
                <button
                  onClick={() => showDeleteConfirm.todoId && deleteTodoFromUser(showDeleteConfirm.todoId)}
                  disabled={loading}
                  className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 disabled:opacity-50 transition-colors"
                >
                  {loading ? '删除中...' : '确认删除'}
                </button>
              </div>
            </div>
          </div>
        )}

        {/* 统计信息 */}
        {stats && (
          <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
            <div className="bg-white rounded-lg shadow p-6">
              <div className="text-2xl font-bold text-blue-600">{stats.total_users}</div>
              <div className="text-gray-600">总用户数</div>
            </div>
            <div className="bg-white rounded-lg shadow p-6">
              <div className="text-2xl font-bold text-green-600">{stats.admin_users}</div>
              <div className="text-gray-600">管理员</div>
            </div>
            <div className="bg-white rounded-lg shadow p-6">
              <div className="text-2xl font-bold text-purple-600">{stats.regular_users}</div>
              <div className="text-gray-600">普通用户</div>
            </div>
            <div className="bg-white rounded-lg shadow p-6">
              <div className="text-2xl font-bold text-orange-600">{stats.total_todos}</div>
              <div className="text-gray-600">总任务数</div>
            </div>
          </div>
        )}

        {/* 主要内容区域 */}
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* 用户列表 */}
          <div className="bg-white rounded-lg shadow">
            <div className="px-6 py-4 border-b border-gray-200">
              <h2 className="text-lg font-semibold text-gray-900">用户列表</h2>
            </div>
            <div className="p-6">
              {loading ? (
                <div className="text-center py-4">加载中...</div>
              ) : (
                <div className="space-y-2">
                  {users.map((user) => (
                    <div
                      key={user.id}
                      className={`p-3 rounded-lg cursor-pointer transition-colors ${
                        selectedUser?.id === user.id
                          ? 'bg-blue-100 border border-blue-300'
                          : 'bg-gray-50 hover:bg-gray-100'
                      }`}
                      onClick={() => handleUserSelect(user)}
                    >
                      <div className="flex items-center justify-between">
                        <div>
                          <div className="font-medium text-gray-900">{user.username}</div>
                          <div className="text-sm text-gray-500">ID: {user.id}</div>
                        </div>
                        <div className={`px-2 py-1 rounded text-xs font-medium ${
                          user.role === 'admin' 
                            ? 'bg-red-100 text-red-800' 
                            : 'bg-green-100 text-green-800'
                        }`}>
                          {user.role === 'admin' ? '管理员' : '用户'}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>

          {/* 任务管理区域 */}
          <div className="lg:col-span-2 bg-white rounded-lg shadow">
            <div className="px-6 py-4 border-b border-gray-200">
              <div className="flex items-center justify-between">
                <h2 className="text-lg font-semibold text-gray-900">
                  {selectedUser ? `${selectedUser.username} 的任务` : '选择用户查看任务'}
                </h2>
                {selectedUser && (
                  <button
                    onClick={() => setShowAddForm(!showAddForm)}
                    className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                  >
                    分配新任务
                  </button>
                )}
              </div>
            </div>
            
            <div className="p-6">
              {!selectedUser ? (
                <div className="text-center py-8 text-gray-500">
                  请从左侧选择一个用户来查看和管理他们的任务
                </div>
              ) : (
                <>
                  {/* 新任务表单 */}
                  {showAddForm && (
                    <div className="mb-6 p-4 bg-gray-50 rounded-lg">
                      <h3 className="text-md font-medium text-gray-900 mb-4">分配新任务</h3>
                      <div className="space-y-4">
                        <div>
                          <label className="block text-sm font-medium text-gray-700 mb-1">
                            任务标题
                          </label>
                          <input
                            type="text"
                            value={newTodo.title}
                            onChange={(e) => setNewTodo({...newTodo, title: e.target.value})}
                            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                            placeholder="输入任务标题"
                          />
                        </div>
                        
                        <div>
                          <label className="block text-sm font-medium text-gray-700 mb-1">
                            任务描述
                          </label>
                          <textarea
                            value={newTodo.description}
                            onChange={(e) => setNewTodo({...newTodo, description: e.target.value})}
                            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                            rows={3}
                            placeholder="输入任务描述（可选）"
                          />
                        </div>
                        
                        <div className="grid grid-cols-2 gap-4">
                          <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">
                              状态
                            </label>
                            <select
                              value={newTodo.status}
                              onChange={(e) => setNewTodo({...newTodo, status: e.target.value as TodoStatus})}
                              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                            >
                              <option value={TodoStatus.PENDING}>待处理</option>
                              <option value={TodoStatus.IN_PROGRESS}>进行中</option>
                              <option value={TodoStatus.COMPLETED}>已完成</option>
                            </select>
                          </div>
                          
                          <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">
                              优先级
                            </label>
                            <select
                              value={newTodo.priority}
                              onChange={(e) => setNewTodo({...newTodo, priority: e.target.value as TodoPriority})}
                              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                            >
                              <option value={TodoPriority.LOW}>低</option>
                              <option value={TodoPriority.MEDIUM}>中</option>
                              <option value={TodoPriority.HIGH}>高</option>
                            </select>
                          </div>
                        </div>
                        
                        <div className="flex gap-2">
                          <button
                            onClick={assignTodoToUser}
                            disabled={loading}
                            className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 transition-colors"
                          >
                            {loading ? '分配中...' : '分配任务'}
                          </button>
                          <button
                            onClick={() => setShowAddForm(false)}
                            className="px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-colors"
                          >
                            取消
                          </button>
                        </div>
                      </div>
                    </div>
                  )}

                  {/* 任务列表 */}
                  <div className="space-y-3">
                    {userTodos.length === 0 ? (
                      <div className="text-center py-8 text-gray-500">
                        该用户暂无任务
                      </div>
                    ) : (
                      userTodos.map((todo) => (
                        <div key={todo.id} className="p-4 border border-gray-200 rounded-lg">
                          <div className="flex items-start justify-between">
                            <div className="flex-1">
                              <h4 className="font-medium text-gray-900 mb-1">{todo.title}</h4>
                              {todo.description && (
                                <p className="text-gray-600 text-sm mb-2">{todo.description}</p>
                              )}
                              <div className="flex gap-2">
                                <span className={`px-2 py-1 rounded text-xs font-medium ${
                                  todo.status === TodoStatus.PENDING ? 'bg-orange-100 text-orange-800' :
                                  todo.status === TodoStatus.IN_PROGRESS ? 'bg-blue-100 text-blue-800' :
                                  'bg-green-100 text-green-800'
                                }`}>
                                  {getStatusLabel(todo.status)}
                                </span>
                                <span className={`px-2 py-1 rounded text-xs font-medium ${
                                  todo.priority === TodoPriority.LOW ? 'bg-gray-100 text-gray-800' :
                                  todo.priority === TodoPriority.MEDIUM ? 'bg-yellow-100 text-yellow-800' :
                                  'bg-red-100 text-red-800'
                                }`}>
                                  优先级: {getPriorityLabel(todo.priority)}
                                </span>
                              </div>
                            </div>
                            <div className="flex items-center gap-2 ml-4">
                              <div className="text-xs text-gray-500">
                                ID: {todo.id}
                              </div>
                              <button
                                onClick={() => showDeleteConfirmDialog(todo.id, todo.title)}
                                className="p-1 text-red-600 hover:bg-red-50 rounded"
                                title="删除任务"
                              >
                                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                </svg>
                              </button>
                            </div>
                          </div>
                        </div>
                      ))
                    )}
                  </div>
                </>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

export default AdminDashboard